<script setup>
import { ref,reactive, nextTick,onActivated,getCurrentInstance,onMounted, watch  } from 'vue'; 
import { useRoute,useRouter } from 'vue-router';
import { ElMessage,ElMessageBox  } from 'element-plus';
import TopBar from '@/components/Topbar/index.vue';
import {getPageProducts} from '@/api/ShopDatabase/index.js'
import getRules from "@/validUtils";
import UploadImg from '@/components/UploadImg/index.vue';
import { uniqueFunc } from '@/utils/common.js'
import { getFieldValue,generateInitials,limitFloat,limitInt,giveFloatMin,giveIntMin } from '@/utils/common.js'
import { useDistInfoStore } from '@/stores/dict.js';
import { getBaseSetting,getAllCommodityExtraAttributes } from '@/api/ShopDatabase/goodsSetting.js'
import { getProjectList } from '@/api/ShopDatabase/project.js'
import { keepCombo,getComboDetail } from '@/api/ShopDatabase/package'
import { closeTag } from '@/utils/globalWay';
import useDiffValue from '@/views/EngageManagement/ShopDatabase/ProductManagement/Hooks/useDiffValue.js'
import { minSalePriceRules } from '../ProductManagement/Components/rules'
const route = useRoute();
const router = useRouter();
const backValue = ref('PackageManagementIndex');
const tabName = ref("编辑套餐");
const moduleType = ref("基础信息");
const distInfoStore = useDistInfoStore();
const formRef = ref(null);
const shopFormRef = ref(null);
const form = ref({
    code:"",
    comboName:"",
    mnemonicCode:"",
    businessBrandId:[],
    activityImg:[],
    validity:"",
    salesState:1,
    salesClassIdList:[],
    retailPrice:"",
    costPrice:"",
    minSellingPrice:'', //最低售价
    needValue:"1"
})
const shopForm = ref({
    mallInfoPut:1,
    mallInfoValidity:"",
    mallInfoDetails:"",
    mallPictureList:[],
    purchaseNotes:""
})
const brandList = computed(()=>{
    return distInfoStore.getDistInfo("经营品牌").map(lis=>{
        return {
            value:lis.id,
            label:lis.permissionName
        }
    })
})
const backValueActivityImg = (img)=>{
    form.value.activityImg = img;
    formRef.value.clearValidate(['activityImg']);
}
const backValueActivityDetailImg = (img)=>{
    shopForm.value.mallPictureList = img;
    shopFormRef.value.validateField('mallInfoDetails')
}
const setMnemonicCode = (value)=>{
    form.value.mnemonicCode = generateInitials(value);
    
}
const classifyList = ref([]);
const typeOptions = ref([]);
const _getBaseSetting = async ()=>{
    classifyList.value = [];
    typeOptions.value = [];
    try{
        let result = await getBaseSetting();
        classifyList.value =  getFieldValue('销售分类',result,'id');
        typeOptions.value = getFieldValue('类别',result,'id');
        formInline.value[2].data = typeOptions.value;
    }catch(e){

    }
}

const comboAttributesList = ref([]);
const _getAllCommodityExtraAttributes = async ()=>{
    comboAttributesList.value = [];
    try{
        let result = await getAllCommodityExtraAttributes();
        if(result.comboAttributesList && result.comboAttributesList.length>0){
            comboAttributesList.value = result.comboAttributesList.filter(value=>value.disabled == 0).map(lis=>{
                if(lis.fieldType == 3 || lis.fieldType == 4){
                    lis.optionContent = lis.optionContent.split(",")
                }
                if(lis.fieldType == 4){
                    return {...lis,fieldValue:[]};
                }else{
                    return {...lis,fieldValue:""};
                }

            })
            console.log(comboAttributesList.value,222);
        }

    }catch(e){
        console.log(e);
    }
}
const rules = ref({
    businessBrandId:[
        { required:true,validator: (rule, value, callback) => {
                if (value.length<=0) {
                    return callback(new Error("请选择经营品牌"));
                }
                return callback();
            }, trigger: "change"
        },
    ],

})
const shopRules = ref({
    mallInfoDetails:[
        { required:true,validator: (rule, value, callback) => {
                if (((value??'') === '') && (shopForm.value.mallPictureList.length<=0)) {
                    return callback(new Error("请输入套餐详情"));
                }
                return callback();
            }, trigger: "change"
        },
    ],

})
const projectData = ref(
    [

    ]
);

const confrimProduct = ()=>{
    if(checkData.value.length>50){
        ElMessage.error('产品添加的上限为50');
        return;
    }
    materialsList.value = [...checkData.value,...checkDataProject.value];
    materialsList.value = materialsList.value.map(lis=>{
        return {
            unitPrice:lis.retailPrice,
            frequency:lis.frequency?lis.frequency:"",
            infoType:1,
            ...lis,
        }
    })
    productFlag.value = false;
}


const formInline = ref([
{
      type: "datePicker",
      prop: ["startDate", "endDate"],
      startPlaceholder: "创建开始时间",
      endPlaceholder: "创建结束时间",
      label: "",
      model: [],
    },
    {
      type: "input",
      prop: 'fuzzyValue',
      placeholder: "产品名称/编号/助记码/条码",
      label: "",
      model: '',
    },
    {
      type: "select",
      placeholder: "类别",
      label: '',
      filterable:true,
      prop: 'categoryId',
      data:[],
      model: "",
    },
    {
        type: "select",
        placeholder: "经营品牌",
        label: '',
        prop: 'businessBrandId',
        multiple:true,
        disabled:true,
        data:distInfoStore.getDistInfo("经营品牌").map(lis=>{
          return {
            value:lis.id,
            label:lis.permissionName
          }
        }),
        model: [],
    },

])
const btnLefts = ref([]);
const btnRights = ref([
])
const tableConfig = ref([
{
      type:'slot',
      label:'产品编号',
      prop:'code',
      width:150,
      slotName:'productCode'
    },
    {
      type:'slot',
      label:'产品名称',
      prop:'productName',
      width:296,
      slotName:'productName'
    },
    {
      label:'产品类别',
      prop:'category',
      width:174
    },
    {
      prop: "businessBrandId",
      label: "经营品牌",
      width:300,
      format:(value)=>{

        let businessBrandId = value.split(',');

        let strArr = distInfoStore.getDistInfo("经营品牌").filter(lis=>{
          return businessBrandId.includes(lis.id)
        }).map(lis=>lis.permissionName)
        return strArr.join('，');
      }
    },
    {
      label:'销售状态',
      prop:'salesState',
      width:100,
      format:(value)=> value ? '正常' : '停售'
    },
    {
      label:'创建时间',
      prop:'createTime',
      width:200
    },
])
const tableLoading = ref(false)
const totalPage = ref(0)
const tableData = ref([]);
const productFlag = ref(false);
const checkData = ref([]);
const seachTable = ref(null);
const handlerSearch = async (formInline)=>{
    
    tableLoading.value = true;
    try{
        if(formInline.businessBrandId && formInline.businessBrandId.length>0){
          formInline.businessBrandId = formInline.businessBrandId.join(',')
        }
        const res = await getPageProducts(formInline);
        totalPage.value = Number(res.total);
        tableData.value = res.records.map(lis=>{
            return {
                ...lis,
                pictureUrl:lis.firstPicture
            }
        })
        tableData.value.forEach(value=>{
            value.infoType = 1;
            value.frequency = "";
            checkData.value.forEach(lis=>{
                if(value.id == lis.id){
                    value.frequency = lis.consumeNum;
                }
            })
        })
        nextTick(()=>{
            toggleSelection();
        })
        tableLoading.value = false;
    }catch(e){
        
        tableLoading.value = false;
    }
}
const selectHandle = (val,row)=>{
  let index = checkData.value.map(value=>value.id).indexOf(row.id);
  if(index >=0){
      removeData([row.id]);
  }else{
      checkData.value = uniqueFunc([row,...checkData.value],'id');
  }

}
const selectAllChange = (col)=>{
  if(col.length>0){
      checkData.value = uniqueFunc([...col,...checkData.value],'id');
  }else{
      let ids = tableData.value.map(value=>value.id);
      removeData(ids);
  }
};
//移除未选中的数据
const removeData = (ids)=>{
    checkData.value = checkData.value.filter(value=>ids.indexOf(value.id) == -1);
};
const toggleSelection = ()=>{
  //获取所有选中的id
  let ids = checkData.value.map(value=>value.id);
  //过滤获取相同值
  let repeatValue = tableData.value.filter(value=>ids.indexOf(value.id) != -1);
  seachTable.value.checkHaveData(repeatValue);
};
const materialsList = ref([]);
const formInlineProject = ref([
{
      type: "datePicker",
      prop: ["startDate", "endDate"],
      startPlaceholder: "创建开始时间",
      endPlaceholder: "创建结束时间",
      label: "",
      model: [],
    },
    {
      type: "input",
      prop: "fuzzyValue",
      placeholder: "项目名称/编号/助记码",
      label: "",
      model: "",
    },

    {
        type: "select",
        placeholder: "经营品牌",
        label: '',
        prop: 'businessBrandId',
        multiple:true,
        disabled:true,
        data:distInfoStore.getDistInfo("经营品牌").map(lis=>{
          return {
            value:lis.id,
            label:lis.permissionName
          }
        }),
        model: [],
    },

])
const btnLeftsProject = ref([]);
const btnRightsProject = ref([
])
const tableConfigProject = ref([
{
      prop: "code",
      label: "项目编号",
      type:"slot",
      slotName:'code',
      width:150
    },
    {
      prop: "projectName",
      label: "项目名称",
      type:"slot",
      slotName:'projectName',
      width:310
    },
    {
      prop: "businessBrandId",
      label: "经营品牌",
      width:300,
      format:(value)=>{

        let businessBrandId = value.split(',');

        let strArr = distInfoStore.getDistInfo("经营品牌").filter(lis=>{
          return businessBrandId.includes(lis.id)
        }).map(lis=>lis.permissionName)
        return strArr.join('、');
      }
    },
    {
      prop: "salesClass",
      label: "销售分类",
      width:100
    },
    {
      prop: "existsDisposables",
      label: "关联耗材",
      width:200,
      format:(value)=>{
        return ["否","是"][value]
      }
    },
    {
      prop: "salesState",
      label: "销售状态",
      width:100,
      format:(value)=>{
        return ["","正常","停售"][value]
      }
    },
    {
      prop: "createTime",
      label: "创建时间",
      width:250
    },
])
const tableLoadingProject = ref(false)
const totalPageProject = ref(0)
const tableDataProject = ref([]);
const projectFlag = ref(false);
const checkDataProject = ref([]);
const seachTableProject = ref(null);
const handlerSearchProject = async (formInline)=>{
    tableLoadingProject.value = true;
    try{
        if(formInline.businessBrandId && formInline.businessBrandId.length>0){
          formInline.businessBrandId = formInline.businessBrandId.join(',')
        }
        let result = await getProjectList(formInline)
        tableDataProject.value = result.records;
        totalPageProject.value = Number(result.total);
        tableDataProject.value.forEach(value=>{
            value.infoType = 2;
            value.frequency = "";
            checkData.value.forEach(lis=>{
                if(value.id == lis.id){
                    value.frequency = lis.consumeNum;
                }
            })
        })
        nextTick(()=>{
            toggleSelectionProject();
        })
        tableLoadingProject.value = false;
    }catch(e){
        tableLoadingProject.value = false;
    }
}
const selectHandleProject = (val,row)=>{
  let index = checkDataProject.value.map(value=>value.id).indexOf(row.id);
  if(index >=0){
      removeData([row.id]);
  }else{
    checkDataProject.value = uniqueFunc([row,...checkDataProject.value],'id');
  }

}
const selectAllChangeProject = (col)=>{
  if(col.length>0){
    checkDataProject.value = uniqueFunc([...col,...checkDataProject.value],'id');
  }else{
      let ids = tableDataProject.value.map(value=>value.id);
      removeData(ids);
  }
};
//移除未选中的数据
const removeDataProject = (ids)=>{
    checkDataProject.value = checkDataProject.value.filter(value=>ids.indexOf(value.id) == -1);
};
const toggleSelectionProject = ()=>{
  //获取所有选中的id
  let ids = checkDataProject.value.map(value=>value.id);
  //过滤获取相同值
  let repeatValue = tableDataProject.value.filter(value=>ids.indexOf(value.id) != -1);
  seachTableProject.value.checkHaveData(repeatValue);
};
const delMaterials = (index,type,row)=>{
    ElMessageBox.confirm(`确定删除该${ type==1?'产品':'项目'}吗？`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'error',
        beforeClose: async (action, instance, done) => {
            if (action === 'confirm') {
                if(type===1){
                    const id = row.id
                    const i = checkData.value.findIndex(item =>item.id === id)
                    checkData.value.splice(i, 1)
                }else{
                    const id = row.id
                    const i = checkDataProject.value.findIndex(item =>item.id === id)
                    checkDataProject.value.splice(i, 1)
                }
                materialsList.value.splice(index,1);

                done()
            } else {
                done()
            }
        }
    })
}

const openProductList = ()=>{

    formInline.value[3].model = form.value.businessBrandId;
    productFlag.value = true;
    checkData.value = [...materialsList.value.filter(lis=>lis.infoType==1)];

}
const openProjectList = ()=>{

    formInlineProject.value[2].model = form.value.businessBrandId;
    projectFlag.value = true;
    checkDataProject.value = [...materialsList.value.filter(lis=>lis.infoType==2)];
}
const cancelProductList = ()=>{
    productFlag.value = false;
    checkData.value = [...materialsList.value.filter(lis=>lis.infoType==1)];
}
const cancelProjectList = ()=>{
    projectFlag.value = false;
    checkDataProject.value = [...materialsList.value.filter(lis=>lis.infoType==2)];
}
const confrimProject = ()=>{
    if(checkData.value.length>50){
        ElMessage.error('项目添加的上限为50');
        return;
    }
    materialsList.value = [...checkData.value,...checkDataProject.value];
    materialsList.value = materialsList.value.map(lis=>{
        return {
            unitPrice:lis.retailPrice,
            frequency:lis.frequency?lis.frequency:"",
            infoType:2,
            ...lis,
        }
    })
    projectFlag.value = false;
}

const changeMallInfoPut = ()=>{
    shopForm.value.mallInfoValidity = "";
    shopForm.value.mallInfoDetails = "";
    shopForm.value.mallPictureList = [];
    shopForm.value.purchaseNotes = "";
}
const keepLoading = ref(false);
let oldDetails = {};
const submit  = ()=>{
    formRef.value.validate((validOne, fields,msg)=>{
        if(validOne){
            shopFormRef.value.validate(async (validTwo, fields)=>{
                if(validTwo){
                    // if(form.value.activityImg.length<=0){
                    //     ElMessage.error('套餐图片未传');
                    //     moduleType.value = '基础信息';
                    //     return;
                    // }
                    if(materialsList.value.length<=0){
                        ElMessage.error('至少添加一个产品/项目');
                        moduleType.value = '基础信息';
                        return;
                    }

                    const newValue = {
                        retailPrice:+form.value.retailPrice,
                        salesStatus:+form.value.salesState,
                    }
                    const isDiff = await useDiffValue(oldDetails,newValue);
                    if(!isDiff) return
                    let params = {
                        id:uuid.value,
                        add:0,
                        code:form.value.code,
                        comboName:form.value.comboName,
                        mnemonicCode:form.value.mnemonicCode,
                        businessBrandId:form.value.businessBrandId.join(','),
                        comboPictureList:[...form.value.activityImg.map(value=>{
                            return {
                                url:value,
                                sourceType:3    
                            }
                        }),...shopForm.value.mallPictureList.map(value=>{
                            return {
                                url:value,
                                sourceType:5    
                            }
                        })],
                        validity:form.value.validity,
                        salesState:form.value.salesState,
                        salesClass:form.value.salesClassIdList.map(item => classifyList.value.find(f=>f.value===item).label).join(','),
                        salesClassIdList:form.value.salesClassIdList,
                        retailPrice:form.value.retailPrice,
                        costPrice:form.value.costPrice,
                        minSellingPrice:form.value.minSellingPrice,//最低售价
                        mallInfoPut:shopForm.value.mallInfoPut,
                        mallInfoValidity:shopForm.value.mallInfoValidity,
                        mallInfoDetails:shopForm.value.mallInfoDetails,
                        purchaseNotes:shopForm.value.purchaseNotes,
                        attributeList:[],
                        comboDetailList:[]
                    }

                    comboAttributesList.value.forEach(lis=>{
                        params.attributeList.push({
                            sourceType:3,
                            extraAttributesName:lis.fieldName,
                            optionContent:lis.fieldType == 3 || lis.fieldType ==4?lis.optionContent.join(','):"",
                            fieldType:lis.fieldType,
                            extraAttributesValue:lis.fieldType ==4?lis.fieldValue.join(','):lis.fieldValue,
                            extraAttributesId:lis.id
                        })
                    })
                    materialsList.value.forEach(lis=>{
                        params.comboDetailList.push({
                            baseId:lis.id,
                            sourceType:lis.infoType ==1?1:2,
                            times:Number(lis.frequency),
                            unitPrice:lis.unitPrice,
                            commodityName:lis.productName || lis.projectName,
                            commodityCode:lis.code,
                            commodityPicture:lis.pictureUrl || lis.firstPicture

                        })
                    })

                    keepLoading.value = true;
                    try{
                        await keepCombo(params)
                        ElMessage.success('编辑成功');
                        closeTag(route.name);
                        router.replace({name:backValue.value});
                    }catch(e){
                        console.log(e);
                    }finally{
                        keepLoading.value = false;
                    }
                 

                }else{
                    ElMessage.error('商城信息未填写完整');
                    moduleType.value = '商城信息';
                }
            });
        }else{
            ElMessage.error('基础信息未填写完整');
            moduleType.value = '基础信息';
        }
    });
}
const editFrequency = ()=>{

    checkData.value = materialsList.value.filter(lis=>lis.infoType == 1);    
    checkDataProject.value = materialsList.value.filter(lis=>lis.infoType == 2);    
}
const changeSalesState = (val)=>{
    shopForm.value.mallInfoDetails = "";
    shopForm.value.mallInfoPut = val;
    shopForm.value.mallPictureList = [];
}
const pageLoading = ref(false);
const uuid = ref(route.query.id || "");
const _getComboDetail = async ()=>{
    pageLoading.value = true;
    try{
        await _getBaseSetting();
        await _getAllCommodityExtraAttributes();
        let result = await getComboDetail({id:uuid.value});
        oldDetails = {
            retailPrice:+result.retailPrice,
            salesStatus:+result.salesState,
        }
        form.value = {
            code:result.code,
            comboName:result.comboName,
            mnemonicCode:result.mnemonicCode,
            businessBrandId:result.businessBrandId?result.businessBrandId.split(","):[],
            activityImg:result.comboPictureList?result.comboPictureList.map(value=>{
                return value.url
            }):[],
            validity:result.validity,
            salesState:result.salesState,
            salesClassIdList:result.salesClassIdList,
            retailPrice:result.retailPrice,
            costPrice:result.costPrice,
            minSellingPrice:result.minSellingPrice,//最低售价
            needValue:"1"
        }
        shopForm.value = {
            mallInfoPut:result.mallInfoPut,
            mallInfoValidity:result.mallInfoValidity,
            mallInfoDetails:result.mallInfoDetails,
            mallPictureList:result.mallPictureList?result.mallPictureList.map(value=>{
                return value.url
            }):[],
            purchaseNotes:result.purchaseNotes
        }
        checkData.value = result.productList.map(lis=>{
            return {
                ...lis,
                id:lis.baseId,
                infoType:1,
                frequency:lis.times,
                unitPrice:lis.unitPrice,
                productName:lis.commodityName,
                code:lis.commodityCode,
                pictureUrl:lis.commodityPicture
            }
        })
        checkDataProject.value = result.projectList.map(lis=>{
            return {
                ...lis,
                id:lis.baseId,
                infoType:2,
                frequency:lis.times,
                unitPrice:lis.unitPrice,
                projectName:lis.commodityName,
                code:lis.commodityCode,
                firstPicture:lis.commodityPicture
            }
        })
        materialsList.value = [...checkData.value,...checkDataProject.value];
        result.attributeList.forEach(info=>{
            comboAttributesList.value.forEach(lis=>{
                if(info.extraAttributesId == lis.id){
                    lis.fieldValue = lis.fieldType ==4?info.extraAttributesValue.split(',').filter(value=>value!=""):info.extraAttributesValue
                }
            })
        })
        
    }catch(e){
        console.log(e);
    }finally{
        pageLoading.value = false;
    }
}
_getComboDetail();
onActivated(()=>{
    if(uuid.value !== route.query.id){
        uuid.value = route.query.id;
        _getComboDetail();
    }

})
const frequencyRules = (index)=>{
    return [{
        required: true,
        validator: (rule, value, callback) => {
            if(materialsList.value[index].frequency){
                callback();
            }else{
                callback(new Error('请输入次数/数量'));
            }
        },
        trigger: 'blur'
    }]
}

const blurRetailPrice = ()=>{
    form.value.retailPrice=giveFloatMin(form.value.retailPrice)
        if(form.value.minSellingPrice){
             formRef.value.validateField(['minSellingPrice'])
        }
    }

</script>
<template>
    <div class="page-contain">
        <TopBar :backValue="backValue" :tabName="tabName">
            <template #operate>

                <el-button type="primary" style="min-width: 68px" @click="submit" :loading="keepLoading">保存</el-button>
            </template>
        </TopBar>
        <div class="info-contain" v-loading="pageLoading">
            <div class="btn-opea">
                <el-radio-group v-model="moduleType">
                    <el-radio-button label="基础信息" />
                    <el-radio-button label="商城信息" />
                </el-radio-group>
            </div>
            <div class="info-lis" v-show="moduleType == '基础信息'">

                <el-form :model="form" label-width="90px" :rules="rules" ref="formRef">
                    <div class="lis-head">
                        <div class="icon-view">
                            <div class="icon-view-on"></div>
                        </div>
                        <span class="label-name">基础属性</span>

                    </div>
                    <div class="lis-item">
                        <div class="lis-i">
                            <el-form-item label="套餐编号"  required prop="needValue">
                                <el-input v-model="form.code" placeholder="保存后自动生成" disabled style="width:260px"/>
                            </el-form-item>
                        </div>
                        <div class="lis-i">
                            <el-form-item label="套餐名称" :rules="getRules('input', '套餐名称')" prop="comboName">
                                <el-input v-model="form.comboName" placeholder="请输入" style="width:260px" :maxlength="50" @blur="setMnemonicCode(form.comboName)"/>
                            </el-form-item>
                        </div>
                        <div class="lis-i">
                            <el-form-item label="助记码" :rules="getRules('input', '助记码')" prop="mnemonicCode">
                                <el-input v-model="form.mnemonicCode" placeholder="请输入" style="width:260px"/>
                            </el-form-item>
                        </div>
                    </div>
                    <div class="lis-item">
                        <div class="lis-i">
                            <el-form-item label="经营品牌" prop="businessBrandId" >
                                <el-select v-model="form.businessBrandId" placeholder="请选择"  clearable v-selectClose style="width:260px" multiple collapse-tags>
                                    <el-option :label="item.label" :value="item.value" v-for="(item,index) in brandList" :key="index"/>
                                </el-select> 
                            </el-form-item>
                        </div>


                    </div>
                    <div class="lis-item">
                        <div class="lis-i" style="width:100%">
                            <el-form-item label="套餐图片">
                                <div style="width:100%;position: relative;">
                                    <UploadImg :multiple="true" @backValue="backValueActivityImg"  :imageListUrlInfo="form.activityImg">
                                    </UploadImg>
                                    <div style="font-size:12px;color:#666666;line-height:12px;width:100%;margin-top:4px">
                                        支持jpg、jpeg、png格式，图片比例1:1；建议为300*300，最多5张，单张不超过5M
                                    </div>
                                </div>

  
                            </el-form-item>
                        </div>
                    </div>
                    <div class="lis-item">
                        <div class="lis-i" style="width:100%">
                            <el-form-item label="套餐内容" prop="needValue" required>
                                <div style="width:100%">
                                    <el-button plain :type="form.businessBrandId.length>0?'primary':''" @click="openProjectList()" :disabled="form.businessBrandId.length>0?false:true">
                                        <img v-if="form.businessBrandId.length>0" src="@/assets/icon/btn-add-blue.png" alt="" style="margin-right:8px;width:14px;height:14px" >
                                        <img v-else src="@/assets/icon/btn-add-gray.png" alt="" style="margin-right:8px;width:14px;height:14px" >
                                        添加项目
                                    </el-button>
                                    <el-button plain :type="form.businessBrandId.length>0?'primary':''" @click="openProductList()" :disabled="form.businessBrandId.length>0?false:true">
                                        <img v-if="form.businessBrandId.length>0" src="@/assets/icon/btn-add-blue.png" alt="" style="margin-right:8px;width:14px;height:14px" >
                                        <img v-else src="@/assets/icon/btn-add-gray.png" alt="" style="margin-right:8px;width:14px;height:14px" >
                                        添加产品
                                    </el-button>
                                </div>
                                <div style="font-size:12px;color:#666666;line-height:12px;width:100%;margin-top:8px">
                                    选择经营品牌后，才可添加项目/产品
                                </div>
                                <div style="width:100%;margin-top:8px" v-if="materialsList && materialsList.length>0">
                                    <el-table :data="materialsList" style="width: 100%" stripe>
                                        <el-table-column prop="name" label="名称">
                                            <template #default="scoped">
                                                <span v-if="scoped.row.infoType == 1">
                                                    <el-tooltip
                                                        class="box-item"
                                                        effect="dark"
                                                        :content="scoped.row.productName"
                                                        placement="top"
                                                    >
                                                        <div class="content-view">
                                                            {{ scoped.row.productName }} 
                                                        </div>
                                                    </el-tooltip>
                                                    <!-- {{ scoped.row.productName }} -->
                                                </span>
                                                <span v-else>
                                                    <el-tooltip
                                                        class="box-item"
                                                        effect="dark"
                                                        :content="scoped.row.projectName"
                                                        placement="top"
                                                    >
                                                        <div class="content-view">
                                                            {{ scoped.row.projectName }} 
                                                        </div>
                                                    </el-tooltip>
                                                    <!-- {{ scoped.row.projectName }} -->
                                                </span>
                                            </template>
                                        </el-table-column>
                                        <el-table-column prop="type" label="类型">
                                            <template #default="scoped">
      
                                                {{ ["","产品","项目"][scoped.row.infoType] }}
                                            </template>
                                        </el-table-column>

                                        <el-table-column prop="name" label="次数/数量">
                                            <template #default="scoped">
                                                <el-form-item :prop="`materialsList.value.${scoped.$index}.frequency`" label="" :inline-message="true" :rules="frequencyRules(scoped.$index)">
                                                    <el-input
                                                        v-model="scoped.row.frequency"
                                                        @input="()=>{scoped.row.frequency=limitInt(scoped.row.frequency)}"
                                                        @blur="()=>{scoped.row.frequency=giveIntMin(scoped.row.frequency)}"
                                                        size="small"
                                                        style="width:120px"
                                                        placeholder="请输入"
                                                        @change="editFrequency"
                                                    />
                                                </el-form-item>
                                            </template>
                                        </el-table-column>
                                        <el-table-column prop="unitPrice" label="单价"></el-table-column>
                                        <el-table-column  label="价值金额">
                                            <template #default="scoped">

                                                <span v-if="scoped.row.frequency>0">{{ (Number(scoped.row.unitPrice) * Number(scoped.row.frequency)).toFixed(2) }}</span>
                                                <span v-else>-</span>
                                            </template>
                                        </el-table-column>
                                        <el-table-column label="零售价">
                                            <template #default>
                                                -
                                            </template>
                                        </el-table-column>
                                        <el-table-column label="零售金额">
                                            <template #default>
                                                -
                                            </template>
                                        </el-table-column>
                                        <el-table-column label="操作" fixed="right" width="120">
                                            <template #default="scoped">
                                                <el-button type="danger" plain size="small" @click="delMaterials(scoped.$index,scoped.row.infoType,scoped.row)">
                                                    删除
                                                </el-button>
                                            </template>
                                        </el-table-column>
                                    </el-table>
                                </div>

                            </el-form-item>
                        </div>
                    </div>
                    <div class="is-item">
                        <div class="lis-i" style="width:100%">
                            <el-form-item label="套餐有效期" >
                                <el-input
                                    v-model="form.validity"
                                    @input="()=>{form.validity=limitInt(form.validity,3)}"
                                    @blur="()=>{form.validity=giveIntMin(form.validity)}"
    
                                    style="width:120px"
                                    placeholder="请输入"
                                />
                                <span style="line-height: 14px;color: #000000;font-size: 14px;margin-left:8px">天有效</span>
                                <div style="font-size:12px;color:#666666;line-height:12px;width:100%;margin-top:8px">
                                    如套餐包含项目，有效期将在用户核销项目的第一次生效
                                </div>
                            </el-form-item>
                        </div>
                    </div>
                    <div class="lis-item">
                        <div class="lis-i" style="width:100%">
                            <el-form-item label="销售状态" prop="salesState" :rules="getRules('select', '销售状态')">
                                <el-radio-group v-model="form.salesState" class="ml-4" @change="changeSalesState">
                                    <el-radio :label="1">正常</el-radio>
                                    <el-radio :label="2">停售</el-radio>
                                </el-radio-group>
                                <div style="font-size:12px;color:#666666;line-height:12px;width:100%;margin-top:3px">
                                    设置针对经营该商品的所有门店生效。正常时，门店可在线上线下对外销售商品
                                </div>
                            </el-form-item>
                        </div>
                    </div>
                    <div class="lis-item">
                        <div class="lis-i">
                            <el-form-item label="销售分类" :rules="getRules('select', '销售分类')" prop="salesClassIdList">
                                <el-select v-model="form.salesClassIdList" placeholder="请选择"  clearable v-selectClose style="width:260px" multiple collapse-tags>
                                    <el-option :label="item.label" :value="item.value" v-for="(item,index) in classifyList" :key="index"/>
                                </el-select> 
                            </el-form-item>
                        </div>
                        <div class="lis-i">
                            <el-form-item label="零售价" :rules="getRules('input', '零售价')" prop="retailPrice">
                                <el-input 
                                v-model="form.retailPrice" 
                                placeholder="请输入" 
                                style="width:260px" 
                                @input="()=>{form.retailPrice=limitFloat(form.retailPrice)}" 
                                @blur="blurRetailPrice"/>
                            </el-form-item>
                        </div>
                        <div class="lis-i">
                            <el-form-item label="成本价" prop="costPrice">
                                <el-input v-model="form.costPrice" placeholder="请输入" style="width:260px" @input="()=>{form.costPrice=limitFloat(form.costPrice)}" @blur="()=>{form.costPrice=giveFloatMin(form.costPrice)}"/>
                            </el-form-item>
                        </div>
                    </div>
                    <div class="lis-item">
                    <div class="lis-i">
                        <el-form-item label="最低售价" prop="minSellingPrice" :rules="minSalePriceRules(form.retailPrice)">
                    
                            <el-input 
                            style="width: 260px"
                            class="formWidth" 
                            :maxlength="50" 
                            @blur="()=>{form.minSellingPrice=giveFloatMin(form.minSellingPrice)}"
                            @input="()=>{form.minSellingPrice=limitFloat(form.minSellingPrice)}" 
                            v-model.trim="form.minSellingPrice"
                            placeholder="请输入"
                            ></el-input>
                            <div style="font-size:12px;color:#666666;line-height:12px;width:100%;margin-top:10px">门店线上线下销售商品时，商品改价不得低于最低售价</div>
                        </el-form-item>
                    </div>
                </div>

                    <div class="lis-head">
                        <div class="icon-view">
                            <div class="icon-view-on"></div>
                        </div>
                        <span class="label-name">自定义属性</span>

                    </div>
                    <div class="lis-item">
                        <div class="lis-i lis-i-other" v-for="(item,index) in comboAttributesList" :key="index">
                            <div class="l-name">{{ item.fieldName }}</div>
                            <div v-if="item.fieldType == 1">
                                <el-input v-model="item.fieldValue" placeholder="请输入" style="width:260px" :maxlength="100"/>
                            </div>
                            <div v-if="item.fieldType == 2">
                                <el-input v-model="item.fieldValue" placeholder="请输入" style="width:260px"  @input="()=>{item.fieldValue=limitFloat(item.fieldValue)}" @blur="()=>{item.fieldValue=giveFloatMin(item.fieldValue)}"/>
                            </div>
                            <div v-if="item.fieldType == 3">
                                <el-select v-model="item.fieldValue" placeholder="请选择"  clearable v-selectClose style="width:260px">
                                    <el-option :label="lis" :value="lis" v-for="(lis,key) in item.optionContent" :key="key"/>
                                </el-select>  
                            </div>
                            <div v-if="item.fieldType == 4">
                                <el-select v-model="item.fieldValue" placeholder="请选择"  clearable v-selectClose style="width:260px" multiple collapse-tags>
                                    <el-option :label="lis" :value="lis" v-for="(lis,key) in item.optionContent" :key="key"/>
                                </el-select>  
                            </div>
                        </div>
                    </div>
                </el-form>
            </div>
            <div class="info-lis" v-show="moduleType == '商城信息'">
                <el-form :model="shopForm" label-width="120px" ref="shopFormRef" :rules="shopRules">
                    <div class="lis-item">
                        <div class="lis-i" style="width:100%">
                            <el-form-item label="允许上架商城" prop="mallInfoPut" :rules="getRules('select', '允许上架商城')">
                                <el-radio-group :disabled="form.salesState === 2" v-model="shopForm.mallInfoPut" class="ml-4" @change="changeMallInfoPut">
                                    <el-radio :label="1">允许上架</el-radio>
                                    <el-radio :label="2">不允许上架</el-radio>
                                </el-radio-group>
                                <div style="font-size:12px;color:#666666;line-height:12px;width:100%;margin-top:3px">
                                    若允许上架，商品可在商城售卖
                                </div>
                            </el-form-item>
                        </div>

                    </div>
                    <div class="is-item" v-if="shopForm.mallInfoPut === 1">
                        <div class="lis-i" style="width:100%">
                            <el-form-item label="有效期" >
                                <el-input
                                    v-model="shopForm.mallInfoValidity"
                                    @input="()=>{shopForm.mallInfoValidity=limitInt(shopForm.mallInfoValidity,3)}"
                                    @blur="()=>{shopForm.mallInfoValidity=giveIntMin(shopForm.mallInfoValidity)}"
                                    style="width:120px"
                                />
                                <span style="line-height: 14px;color: #000000;font-size: 14px;margin-left:8px">天有效</span>
                                <div style="font-size:12px;color:#666666;line-height:12px;width:100%;margin-top:8px">
                                    顾客下单后的有效期，超过有效期后未到店核销将自动退款
                                </div>
                            </el-form-item>
                        </div>
                    </div>
                    <div class="lis-item" v-if="shopForm.mallInfoPut === 1">
                        <div class="lis-i" style="width:100%">
                            <el-form-item label="套餐详情" prop="mallInfoDetails">
                                <el-input v-model="shopForm.mallInfoDetails" placeholder="请输入" style="width:260px;" :rows="5" type="textarea" :maxlength="500" />
                                <div style="width:100%;position: relative;margin-top: 10px;">
                                    <UploadImg :multiple="true" @backValue="backValueActivityDetailImg"  :imageListUrlInfo="shopForm.mallPictureList" :maxImgLength="20">
                                    </UploadImg>
                                    <div style="font-size:12px;color:#666666;width:100%;">
                                        支持jpg、jpeg、png格式最多20张，单张不超过5M
                                    </div>
                                </div>
                            </el-form-item>
                        </div>

                    </div>
                    <div class="lis-item" v-if="shopForm.mallInfoPut === 1">
                        <div class="lis-i" style="width:100%">
                            <el-form-item label="购买须知" :rules="getRules('input', '购买须知')" prop="purchaseNotes">
                                <el-input v-model="shopForm.purchaseNotes" placeholder="请输入" style="width:260px;" :rows="5" type="textarea" :maxlength="500"/>
                            </el-form-item>
                        </div>

                    </div>
                </el-form>
            </div>
        </div>
        <el-dialog v-model="productFlag" title="选择产品" width="1000px" :before-close="cancelProductList">
            <div style="width:100%;height:500px" v-if="productFlag">
                <SeachTable 
                    :tableType="1"
                    ref="seachTable"
                    :tableSelection="true" 
                    :forms="formInline"
                    :btnLefts="btnLefts"
                    :btnRights="btnRights"
                    :tableLoading="tableLoading"
                    :tableConfig="tableConfig"
                    :tableData="tableData"
                    :totalPage="totalPage"
                    @handlerSearch="handlerSearch"
                    @selectHandle="selectHandle"
                    @selectAllHandle="selectAllChange"
                    :showLine="false"
                    :showBtn="false"
                >
                    <template #productCode="{ row }">
                        <div class="a-link">{{ row.code }}</div>
                    </template>
                    <template #productName="{ row }">
                        <div class="project-info">
                            <div class="img">
                                <el-image
                                :src="row.pictureUrl || 'https://static.91medicine.net/jiuyang/img/404.png'"
                                :zoom-rate="1.2"
                                :preview-src-list="[row.pictureUrl || 'https://static.91medicine.net/jiuyang/img/404.png']"
                                :initial-index="4"
                                style="width:100%;height:100%"
                                />
                            </div>
                            <div class="name-info">
                                <el-tooltip
                                    class="box-item"
                                    effect="dark"
                                    :content="row.productName"
                                    placement="top-start"
                                >
                                    <div class="p1">
                                        {{ row.productName }}
                                    </div>
                                </el-tooltip>
                                <!-- <div class="p1">
                                    {{ row.productName }}
                                </div> -->
                                <div class="p2">
                                    <span>{{ row.specification + (row.specification && row.unit?"/":"") + row.unit }}</span>

                                </div>
                            </div>
                        </div>
                    </template>
                </SeachTable>
            </div>
            <template #footer>
                <div class="dialog-footer">
                    <el-button @click="cancelProductList()">取消</el-button>
                    <el-button type="primary" @click="confrimProduct()">确定</el-button>
                </div>
            </template>
        </el-dialog>
        <el-dialog v-model="projectFlag" title="选择项目" width="1000px" :before-close="cancelProjectList">
            <div style="width:100%;height:500px" v-if="projectFlag">
                <SeachTable 
                    :tableType="1"
                    ref="seachTableProject"
                    :tableSelection="true" 
                    :forms="formInlineProject"
                    :btnLefts="btnLeftsProject"
                    :btnRights="btnRightsProject"
                    :tableLoading="tableLoadingProject"
                    :tableConfig="tableConfigProject"
                    :tableData="tableDataProject"
                    :totalPage="totalPageProject"
                    @handlerSearch="handlerSearchProject"
                    @selectHandle="selectHandleProject"
                    @selectAllHandle="selectAllChangeProject"
                    :showLine="false"
                    :showBtn="false"
                >
                    <template #code="{ row }">
                    <div class="a-link" >{{ row.code }}</div>
                    </template>
                    <template #projectName="{ row }">
                        <div class="project-info">
                            <div class="img">
                                <el-image
                                :src="row.firstPicture"
                                :zoom-rate="1.2"
                                :preview-src-list="[row.firstPicture]"
                                :initial-index="4"
                                style="width:100%;height:100%"
                                />
                            </div>
                            <div class="name-info">
                                <div class="info-show" >
                                    <el-tooltip placement="top">
                                        <template #content>
                                            <div class="tips-info">
                                            {{ row.projectName }}
                                            </div>
                                        </template>
                                        <span class="tip-show">
                                        {{ row.projectName }}
                                        </span>
                                    </el-tooltip>
                                </div>
                            </div>
                        </div>
                    </template>
                </SeachTable>
            </div>
            <template #footer>
                <div class="dialog-footer">
                    <el-button @click="cancelProjectList()">取消</el-button>
                    <el-button type="primary" @click="confrimProject()">确定</el-button>
                </div>
            </template>
        </el-dialog>

    </div>
</template>
<style lang="less" scoped>
:deep(.el-table__inner-wrapper::before){
    display:none;
}
:deep(.el-table th.el-table__cell){
    background: #EBEBEB;
}
:deep(.el-dialog__body){
    padding:0 4px;
}
:deep(.el-table__header){
    tr{
        th{
            &:last-child{
                .cell{
                    border-right: 0px;
                }
            }
        }
    }
}
.page-contain{
    width: 100%;
    height: 100%;
    :deep(.el-table th > .cell){
        border-right: 0;;
    }
    :deep(.el-radio-button:first-child .el-radio-button__inner){
        border-left:1px solid #3480FF;
    }
    .info-contain{
        width: 100%;
        height: calc(100% - 48px);
        box-sizing: border-box;
        padding:16px 24px;
        .btn-opea{
            width: 100%;
            height: 32px;
        }
        .info-lis{
            width: 100%;
            height: calc(100% - 32px);
            box-sizing:border-box;
            padding-top:24px;
            overflow:auto;
            .lis-head{
                    width: 100%;
                    display: flex;
                    justify-content: flex-start;
                    align-items: center;
                    padding-bottom:16px;
                    .icon-view{
                        margin-right: 8px;
                        position: relative;
                        width: 14px;
                        height: 14px;

                        &::before {
                            content: "";
                            position: absolute;
                            top: 0;
                            left: 0;
                            width: 10px;
                            height: 10px;
                            border-radius: 2px;
                            background-color: #10E7F9; 
                        }
                        .icon-view-on{
                            position: absolute;
                            bottom: 0;
                            right: 0;
                            width: 10px;
                            height: 10px;
                            border-radius: 2px;
                            background-color: #3480FF; /* 背景色 */
                        }
                    }
                    .label-name{
                        color: #000000;
                        font-weight: bold;
                        font-size: 14px;
                        margin-right: 8px;
                    }
                    img{
                        width: 14px;
                        height: 14px;
                        cursor: pointer;
                    }
                }
        }
        .lis-item{
            width: 100%;
            display: flex;
            justify-content: flex-start;
            flex-wrap: wrap;
            .lis-i{
                width: calc(100% / 3);
                margin-bottom:10px;
            }
            .lis-i-other{
                display: flex;
                justify-content: flex-start;
                align-items: center;
                .l-name{
                    width: 80px;
                    text-align: right;
                    word-break: break-all;
                    word-wrap: break-word;
                    display: flex;
                    justify-content: flex-end;
                    align-items: center;
                    min-height: 32px;
                    padding: 0 12px 0 0;
                    font-size: var(--el-form-label-font-size);
                    color: var(--el-text-color-regular);
                    line-height: 20px;
                }
                
            }
        }
    }
    :deep(.el-table__row){
        .el-input .el-input__wrapper{
            background: rgba(0,0,0,0);
        }
    }
}
.input-line{
    width: 100%;
    display: flex;
    justify-content: flex-start;
    align-items: center;
    margin-bottom:16px;
    &:last-child{
        margin-bottom:0px;
    }
    img{
        cursor: pointer;
        width: 16px;
        height: 16px;
        margin-left:8px;
    }
}
.project-info{
    width: 100%;
    display: flex;
    justify-content: flex-start;
    align-items: center;

    .img{
        width: 48px;
        height: 48px;
        

    }
    .name-info{
        width:calc(100% - 56px);
        box-sizing: border-box;
        padding-left:8px;
        .p1{
            overflow: hidden;
            display: -webkit-box;
            -webkit-box-orient: vertical;
            -webkit-line-clamp: 2;
            width: 100%;
            color: #222222;
            font-weight: bold;
            line-height: 14px;
            font-size: 14px;
            height: 28px;
        }
        .p2{
            width: 100%;
            margin-top:4px;
            color: #000;
            line-height: 14px;
            font-size: 14px;

        }
    }
}
.info-show{
    width: 100%;
    display: flex;
    justify-content: flex-start;
    align-items: center;
    .tip-show{
        max-width: 100%;
        box-sizing:border-box;
        padding-right:4px;
        font-weight: 400;
        color: #222222;
        overflow: hidden;
        display: -webkit-box;
        -webkit-line-clamp: 2;
        -webkit-box-orient: vertical;
    }
    .text-show{
        max-width: calc(100% - 14px);
        box-sizing:border-box;
        padding-right:4px;
        font-weight: 400;
        color: #222222;
        line-height: 18px;
        word-break: break-all;
        word-wrap: break-word;
    }
    .img{
        width: 14px;
        height: 14px;
        cursor: pointer;

    }
}

.content-view{
  overflow: hidden;
  display: -webkit-box;
  -webkit-box-orient: vertical;
  -webkit-line-clamp: 2;
  width: 100%;
}
</style>